#!/usr/bin/env bash

AUTH_SERVER="https://10.7.20.60/auth"

TOKEN_URI="$AUTH_SERVER/realms/master/protocol/openid-connect/token"
JWKS_URI="$AUTH_SERVER/realms/master/protocol/openid-connect/certs"

USERNAME="incloud"
PASSWD="Inspur2!"

function get-token() {
    res=$(curl -sk -X POST "$TOKEN_URI" \
        -H 'Content-Type: application/x-www-form-urlencoded' \
        --data-urlencode "username=$USERNAME" \
        --data-urlencode "password=$PASSWD" \
        --data-urlencode 'grant_type=password' \
        --data-urlencode 'client_id=admin-cli' | jq -r .access_token)

    echo $res
}

function get-certs() {
    curl -sk $JWKS_URI | jq -r .keys[0].x5c[0] | base64 -d | openssl x509 -inform DER -noout -pubkey
}

token=$(get-token)
public_key="$(get-certs)"

splitted=(${token//./ })
token_header=${splitted[0]}
token_payload=${splitted[1]}
token_sign=${splitted[2]}
rm -rf tmp && mkdir tmp

echo "$public_key" >tmp/key.pub
echo "$token_header.$token_payload" >tmp/data
echo "$token_sign" >tmp/sign

# baas64 urlencoded -> base64

sig_1=$(tr '_-' '/+' < tmp/sign)
sig_2=$(wc -L tmp/sign|awk '{len=4-$1%4;if(len==1){print "="}else if(len==2) {print "=="} }')
echo "$sig_1$sig_2" > tmp/sign.base64

cat tmp/sign.base64|base64 -d| openssl rsautl -verify -pubin -inkey tmp/key.pub |base64 > tmp/sign.verified.base64
cat tmp/data|openssl sha256 > tmp/data.sha256

